
package org.linlinjava.litemall.wx.web;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.ConsumeRecord;
import org.linlinjava.litemall.db.domain.CustAccountbase;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.ConsumeRecordService;
import org.linlinjava.litemall.db.service.CustAccountbaseService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.CaptchaCodeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.linlinjava.litemall.wx.util.WxResponseCode.AUTH_CAPTCHA_UNMATCH;


/**
* <p>说明： 用户钱包表API接口层</P>
* @version: V1.0
* @author: wlx
* @time    2021年02月19日
*
*/
@Api(value = "用户钱包",tags="用户钱包" )
@RestController
@RequestMapping("/wx/custAccountbase")
public class CustAccountbaseController {


	private static final Logger logger = LoggerFactory.getLogger(CustAccountbaseController.class);

     @Autowired
	 CustAccountbaseService custAccountbaseService;

	@Autowired
	ConsumeRecordService consumeRecordService;

	@Autowired
	LitemallUserService userService;

	@Autowired
	LitemallUserService litemallUserService;


	@PostMapping("/upPaykey")
	@ApiOperation(value = "修改支付密码", notes = "修改支付密码+-")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
	})
	public Object upPaykey(@LoginUser Integer userId, @RequestBody String body){
		String paykey = JacksonUtil.parseString(body, "paykey");
		String code = JacksonUtil.parseString(body, "code");

		LitemallUser user = userService.findById(userId);

		//判断验证码是否正确
//		String cacheCode = CaptchaCodeManager.getCachedCaptcha(user.getMobile());
		String cacheCode = "111111";
		if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(code))
			return ResponseUtil.fail(AUTH_CAPTCHA_UNMATCH, "验证码错误");

		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("user_id",userId);
		CustAccountbase custAccountbase = custAccountbaseService.getOne(wrapper);

		custAccountbase.setPayKey(paykey);
		custAccountbaseService.updateById(custAccountbase);


		return ResponseUtil.ok();
	}

	@PostMapping("/setPaykey")
	@ApiOperation(value = "修改支付密码", notes = "设置支付密码")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
	})
	public Object setPaykey(@LoginUser Integer userId, @RequestBody String body){
		String paykey = JacksonUtil.parseString(body, "paykey");

		LitemallUser user = userService.findById(userId);

		//判断验证码是否正确
		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("user_id",userId);
		CustAccountbase custAccountbase = custAccountbaseService.getOne(wrapper);

		custAccountbase.setPayKey(paykey);
		custAccountbaseService.updateById(custAccountbase);


		return ResponseUtil.ok();
	}



	@PostMapping("/getCustAccountbaseById")
	@ApiOperation(value = "查询用户钱包", notes = "查询用户钱包")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
	})
	public Object getCustAccountbaseById(@LoginUser Integer userId){
		logger.info("request param,userId is "+userId);
		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("user_id",userId);
		CustAccountbase custAccountbase = custAccountbaseService.getOne(wrapper);
		custAccountbase.setPayKey(null);

		return ResponseUtil.ok(custAccountbase);
	}


	@PostMapping("/getConsumeRecordById")
	@ApiOperation(value = "查询用户收支记录", notes = "查询用户收支记录")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
			@ApiImplicitParam(dataType = "Integer", name = "changeType",value = "1:全部, 2支出  3收入  4充值 5提现"),
			@ApiImplicitParam(dataType = "Integer", name = "time",value = "不传为所有 传参格式2022 04"),
	})
	public Object getConsumeRecordById(@LoginUser Integer userId,@RequestBody String body){

		Integer changeType = JacksonUtil.parseInteger(body, "changeType");
		String time= JacksonUtil.parseString(body, "time");
		Integer pageNum = JacksonUtil.parseInteger(body, "pageNum");
		Integer pageSize = JacksonUtil.parseInteger(body, "pageSize");


		QueryWrapper<ConsumeRecord>  wrapper = new QueryWrapper();
		wrapper.eq("user_id",userId);

		if (!ObjectUtils.isEmpty(changeType)){
			switch (changeType){
				case 2:
					wrapper.eq("change_type",2);
					break;
				case 3:
					wrapper.eq("change_type",1);
					break;
				case 4:
					wrapper.eq("type",1);
					break;
				case 5:
					wrapper.eq("type",2);
					break;

			}
		}

		if (!ObjectUtils.isEmpty(time)){

		}
		PageHelper.startPage(pageNum,pageSize);


		List<ConsumeRecord> list = consumeRecordService.list(wrapper);
		PageInfo<ConsumeRecord> of = PageInfo.of(list);

//		return consumeRecordService.getConsumeRecordByUserId(userId, type,changeType,pageNum,pageSize);
		return ResponseUtil.ok(of);
	}

//
//
//	@GetMapping("/checkPayKeyIsExist")
//	@ApiOperation(value = "查询用户是否设置了支付密码 0：未设置  1：已设置", notes = "查询用户是否设置了支付密码 0：未设置  1：已设置")
//	@ApiImplicitParams({
//			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
//	})
//	public ResponseUtil checkPayKeyIsExist(Integer userId){
//		logger.info("request param,userId is {} ",userId);
//		return custAccountbaseService.checkPayKeyIsExist(userId);
//	}
//
//
//
//
//	@PostMapping("/updatePayKey")
//	@ApiOperation(value = "更新用户支付密码", notes = "更新用户支付密码")
//	@ApiImplicitParams({
//			@ApiImplicitParam(dataType = "String", name = "phone",value = "手机号码",required = true),
//			@ApiImplicitParam(dataType = "String", name = "payKey",value = "支付密码",required = true),
//			@ApiImplicitParam(dataType = "String", name = "vcode",value = "验证码",required = true)
//	})
//	public ResponseUtil updatePayKey2(String phone,String payKey,String vcode){
//
//
//		return custAccountbaseService.updatePayKey2(phone,payKey, vcode);
//	}
//


//
//
//	
//	
//	@GetMapping("/cash")
//	@ApiOperation(value = "提现", notes = "提现")
//	public ResponseUtil cash(ConsumeRecord consumeRecord){
//
//
//		consumeRecord.setUserId(tokenService.getUserId());
//		AppConfig appConfig=appConfigService.getById(1);
//
//		LocalTime now = LocalTime.now();
//		if (now.compareTo(appConfig.getProhibitRechargeWithdrawalStart()) != -1  && now.compareTo(appConfig.getProhibitRechargeWithdrawalEnd()) != 1){
//			return ResponseUtil.fail(ResultCode.PROHIBIT_RECHARGE_WITHDRAWAL);
//		}
//
//
//
//		Integer sumCount = consumeRecordMapper.getSumCount(consumeRecord.getUserId(), 2);
////		sumCount = consumeRecord.getMoney()+1;
////
////		if (consumeRecord.getMoney()<appConfig.getSingleMinimumWithdrawalAmount()){
////			return ResponseUtil.fail(ResultCode.NO_MIN_WITHDRAW);
////		}
//
//
//
//
//
//
//		//		判断是否超出每日最大提现额度
//		Double sumCharge = consumeRecordMapper.getSumCharge(consumeRecord.getUserId(), 1);
//
//		if (sumCharge+consumeRecord.getMoney()+1 >=  appConfig.getDayMaxRechargeAmountCount() ){
//			return ResponseUtil.fail(-1,"超出当日充值最大金额");
//		}
//
//		if (consumeRecord.getMoney()+1 >=  appConfig.getDayMaxRechargeAmount()){
//			return ResponseUtil.fail(-1,"超出单词充值最大金额");
//		}
//
//		//判断余额是否足够
//		QueryWrapper<CustAccountbase> custAccountbaseQueryWrapper = new QueryWrapper<>();
//		custAccountbaseQueryWrapper.eq("user_id",consumeRecord.getUserId());
//		CustAccountbase custAccountbase = custAccountbaseService.getOne(custAccountbaseQueryWrapper);
//		if (consumeRecord.getMoney()+1 > custAccountbase.getAmount()){
//			return ResponseUtil.fail(ResultCode.NOT_SUFFICIENT_FUNDS);
//		}
//
//		double v1 = consumeRecord.getMoney() * appConfig.getServiceCharge();
//		if (v1<0.01){
//			v1 = 0.01;
//		}
//		//                    需要减去的钱
//		double totalAmount = consumeRecord.getMoney() +v1  +1;
//
//		double actualAmount  = 0D;
//
////                    手续费
//		double serviceCharge = v1 +1;
//
//
//
//		//当需要减去的钱大于当前余额的时候
//		if (totalAmount > custAccountbase.getAmount()){
//			//余额减去提现提现的钱   还需要减去手续费
//			double balance = custAccountbase.getAmount() - consumeRecord.getMoney();
//
////                        这个时候手续费绝对大于余额   拿手续费减去余额 剩下的钱 用提现的钱减去剩余的手续费
//			double v = serviceCharge - balance;
//			//这个钱为最终到账的 钱
//			actualAmount = consumeRecord.getMoney() - v;
//			custAccountbase.setAmount(0D);
//		}else {
//			actualAmount = consumeRecord.getMoney();
//			custAccountbase.setAmount(custAccountbase.getAmount() -totalAmount  );
//		}
//
//		//扣除钱包余额
//		custAccountbaseService.updateById(custAccountbase);
//		String randomString = RandomUtil.randomString(12);
//		//写入消费记录
//		consumeRecord.setUserId(consumeRecord.getUserId());
//		consumeRecord.setType(2);
//		consumeRecord.setTradeNo(randomString);
//		consumeRecord.setMoney(actualAmount);
//		consumeRecord.setChangeType(2);
//		consumeRecord.setStatus(0);
//		consumeRecord.setPayType(8);
//		consumeRecord.setTime(new Date());
//		consumeRecord.setDescs("提现");
//		consumeRecord.setServiceCharge(appConfig.getServiceCharge());
//		consumeRecord.setServiceCharge(appConfig.getServiceCharge());
//		consumeRecord.setCurrentBalance(custAccountbase.getAmount());
//		consumeRecord.setOperationAmount(consumeRecord.getMoney());
//		consumeRecord.setSystemServiceCharge(serviceCharge);
//		consumeRecordService.save(consumeRecord);
//
//
//		ConsumeRecord consumeRecord1 = new ConsumeRecord();
//		//写入消费记录
//		consumeRecord1.setUserId(consumeRecord.getUserId());
//		consumeRecord1.setType(56);
//		consumeRecord1.setTradeNo(randomString);
//		consumeRecord1.setMoney(serviceCharge);
//		consumeRecord1.setChangeType(2);
//		consumeRecord1.setStatus(0);
//		consumeRecord1.setPayType(3);
//		consumeRecord1.setTime(new Date());
//		consumeRecord1.setDescs("提现手续费");
//		consumeRecord1.setServiceCharge(appConfig.getServiceCharge());
//		consumeRecord1.setServiceCharge(appConfig.getServiceCharge());
//		consumeRecord1.setCurrentBalance(custAccountbase.getAmount());
//		consumeRecord1.setOperationAmount(consumeRecord.getMoney() );
//		consumeRecordService.save(consumeRecord1);
//
//
//		return ResponseUtil.suc();
//
//
//	}

//	@GetMapping("/recharge")
//	@ApiOperation(value = "充值", notes = "充值")
//	public ResponseUtil recharge(Integer userId,Double number){
//
//
//		//写入钱包和交易记录
////            Double momey = Integer.valueOf((int) (number * 100)) ;
//		QueryWrapper<CustAccountbase> custAccountbaseQueryWrapper = new QueryWrapper<>();
//		custAccountbaseQueryWrapper.eq("user_id",userId);
//		CustAccountbase custAccountbase = custAccountbaseService.getOne(custAccountbaseQueryWrapper);
//		custAccountbase.setAmount(custAccountbase.getAmount() + number);
//		custAccountbaseService.updateById(custAccountbase);
//
//
//
//
//		return ResponseUtil.suc(custAccountbase);
//
//	}



}
